import os
from PIL import Image
'''
图片压缩工具，不改变长宽比，将图片压缩到指定存储大小
'''

fileSize=1024*1024
fileSize=500*1024
source="D:\\OneDrive\\知识\\日常影音"

def compressImage(path):
    for filename in os.listdir(path):
 
        srcfile = os.path.join(path, filename)
        # 筛选图片文件
        if (os.path.isfile(srcfile) and (
                filename.upper().endswith('.JPG') or filename.upper().endswith('.BMP')
                or filename.upper().endswith('.PNG')
                or filename.upper().endswith('.GIF')
                or filename.upper().endswith('.JPEG')
        ) ):
            try:
                compress_size(srcfile)
            except Exception as re:
                print(srcfile + "   error!")
                print(re)

        if os.path.isdir(srcfile):
            compressImage(srcfile)


def compress_size(outfile):
    if os.path.getsize(outfile)<=fileSize:
        return 
    

    size=0
    num=0
    while True:
        if os.path.getsize(outfile)>fileSize:
            im = Image.open(outfile)
            x, y = im.size
            if size==0:
                size=700
            else:
                size=int(size*0.95)

            if x>y: #宽大于高
                #宽度大于1024
                if num==0:
                    size=1200

            y_s = int(y*size/x)
            im = im.resize((size, y_s), Image.ANTIALIAS)

            # out = im.resize((int(x*k), int(y*k)), Image.ANTIALIAS)  # 最后一个参数设置可以提高图片转换后的质量
            im.save(outfile)  # quality为保存的质量，从1（最差）到95（最好），此时为85
            num+=1
        else:
            break
    print(outfile ,"success！ ")


compressImage(source)
